<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div contenteditable="true" id="test">
      <p>
        <math xmlns="http://www.w3.org/1998/Math/MathML" class="wrs_chemistry">
          <mover>
            <mo>&#8594;</mo>
            <mn>25</mn>
          </mover>
        </math>
      </p>
    </div>

    <button id="btn">点我</button>
    <script>
      var ele = document.getElementById('test')
      var btn = document.getElementById('btn')
      ele.addEventListener('keyup', function ($event) {})
      btn.addEventListener('click', function ($event) {
        ele.focus()
        pasteHtmlAtCaret('<b>testsss</b>')
      })

      function pasteHtmlAtCaret(html) {
        var sel, range
        if (window.getSelection) {
          // IE9 and non-IE
          sel = window.getSelection()

          if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0)
            console.log('[ range ]-29', range)
            range.deleteContents()

            var el = document.createElement('div')
            el.innerHTML = html
            var frag = document.createDocumentFragment()
            var node
            var lastNode
            while ((node = el.firstChild)) {
              lastNode = frag.appendChild(node)
            }
            range.insertNode(frag)

            // Preserve the selection
            if (lastNode) {
              /*               range = range.cloneRange()
              range.setStartAfter(lastNode)
              range.collapse(true)
              sel.removeAllRanges()
              sel.addRange(range) */
            }
          }
        }
      }
    </script>
  </body>
</html>
